import axios from "axios"
import React from 'react';
import { useEffect, useState } from "react"
import { useSelector } from "react-redux"
import Table from "../common/Table";
import Image from "next/image";
import { toast } from "react-toastify";
import { useRouter } from "next/router";

const SavedImages = () => {

    const { token } = useSelector(state => state.user)

    const [isLoading, setIsLoading] = useState(false)

    const router = useRouter()

    useEffect(() => {
        if (token) {
            loadSavedImages()
        }
    }, [token])


    const [datas, setDatas] = useState([])

    const loadSavedImages = async () => {
        setIsLoading(true)
        const response = await axios.post('/api/news/list', { page: 1, size: 10 })
        setIsLoading(false)
        setDatas(response.data.data)
    }

    const columns = [
        { label: "缩略图", key: "url", type: "image", render: (row) => <Image src={row.url} width={100} height={100} /> },
        { label: "标题", key: "title" },
        { label: "作者", key: "author" },
        { label: "发布时间", key: "created", type: "date" }
      ];
    
    
      const actions = [
        // {
        //   label: "查看",
        //   className: "btn-primary",
        //   onClick: (row) => {
        //     window.location.href = `/account/show-news?id=${row["_id"]}`
        //   }
        // },
        {
          label: "編集",
          className: "btn-primary",
          onClick: (row) => {
            router.push(`/account/edit-news?id=${row["_id"]}`)
          }
        },
        {
          label: "削除",
          className: "btn-error",
          onClick: async (row) => {
            let response = await axios.post('/api/news/del', { id: row["_id"]})
            if (response.data.code == 200) {
              toast.success("削除しました")
              loadSavedImages()
            } else {
              toast.error("削除に失敗しました")
            }

          }
        }
      ];


    return (
        <>
            <h2 className="text-xl font-bold text-center">ニュースマネジメント</h2>
            {isLoading && <div className="mt-12 text-center"><span className="loading"></span></div>}
            {/* <div className="flex justify-end mt-4">
                <button className="btn btn-primary">新規作成</button>
                <button className="btn btn-second ml-2">削除</button>
            </div> */}

            <div className="grid mt-8">
                <div className="overflow-x-auto">
                <Table columns={columns} data={datas} actions={actions} pageSize={5} />
                </div>

            </div>

        </>
    )
}

export default SavedImages